import { Card, Space, Button, DatePicker, Select, Modal, Tabs, message, Upload, Input, Flex, Typography, Popconfirm, Progress } from "antd";
import { useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import { setShowBtnTool } from "@/store/modules/style";
import { exportgenerateAPI } from "@/apis";
import { InboxOutlined, DownloadOutlined, SyncOutlined } from '@ant-design/icons';
import axios from 'axios'

export default function ReportCreateProgress({ data }) {
  const [messageApi, contextHolder] = message.useMessage();
  const [progress, setProgress] = useState(0);
  const [progressStatus, setProgressStatus] = useState('active');
  const [generating, setGenerating] = useState(false);
  const [generatedUUID, setGeneratedUUID] = useState(null);
  const [timer, setTimer] = useState(null);

  const handleDownload = (uuid) => {
    const gsmc = data.company_info[0].GSMC;
    axios.get(`http://192.168.1.188:9000/kshx/download-reportfile?uuid=${uuid}`, {
      responseType: 'blob',
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('kshxtoken'),
      },
    }).then((res) => {
      const blob = new Blob([res.data], { type: res.headers['content-type'] });
      const fileName = gsmc + '.docx';
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
    }).catch((err) => {
      console.error('文件下载失败:', err);
      messageApi.error('文件下载失败！');
    });
  };

  const handleGenerate = () => {
    setGenerating(true);
    setProgress(0);
    setProgressStatus('active');
    setGeneratedUUID(null);

    const interval = setInterval(() => {
      setProgress(prev => (prev >= 90 ? prev : prev + 5));
    }, 300);
    setTimer(interval);

    exportgenerateAPI({ company: data.company_info[0].GSMC })
      .then((res) => {
        clearInterval(interval);
        setTimer(null);
        if (res.code === 200) {
          setGeneratedUUID(res.data);
          setProgress(100);
          setProgressStatus('success');
          messageApi.success(res.message);
        } else {
          setProgress(100);
          setProgressStatus('exception');
          messageApi.error(res.message || '生成失败！');
        }
      })
      .catch(() => {
        clearInterval(interval);
        setTimer(null);
        setProgress(100);
        setProgressStatus('exception');
        messageApi.error('报告生成失败！');
      });
  };

  return (
    <div>
        {contextHolder}

        {/* 初始状态 */}
        {!generating && !generatedUUID && progressStatus !== 'exception' && (
        <Flex justify="center" align="center" style={{ marginTop: 20 }}>
            <Button
            type="primary"
            style={{
                backgroundColor: '#67C23A',
                borderColor: '#67C23A',
                color: 'white',
            }}
            onClick={handleGenerate}
            >
            开始生成报告
            </Button>
        </Flex>
        )}

        {/* 生成中 + 红色错误状态下显示进度条 */}
        {(generating || progressStatus === 'exception') && (
        <Progress
            percent={progress}
            status={progressStatus}
            style={{ marginTop: 16 }}
        />
        )}

        {/* 错误状态（非生成中）下显示重新生成 */}
        {progressStatus === 'exception' && !generating && (
        <Flex justify="center" align="center" style={{ marginTop: 20 }}>
            <Button
            type="primary"
            style={{
                backgroundColor: '#67C23A',
                borderColor: '#67C23A',
                color: 'white',
            }}
            onClick={handleGenerate}
            >
            重新生成报告
            </Button>
        </Flex>
        )}

        {/* 成功状态下显示下载与重新生成 */}
        {generatedUUID && progress === 100 && progressStatus === 'success' && (
        <Flex justify="space-between" align="center" style={{ marginTop: 20 }}>
            <Button
            type="primary"
            onClick={() => handleDownload(generatedUUID)}
            style={{
                backgroundColor: '#67C23A',
                borderColor: '#67C23A',
                color: 'white',
            }}
            >
            下载报告
            </Button>
            <Button
            type="primary"
            style={{
                backgroundColor: '#67C23A',
                borderColor: '#67C23A',
                color: 'white',
            }}
            onClick={handleGenerate}
            >
            重新生成报告
            </Button>
        </Flex>
        )}
    </div>
  );
}